﻿/**
 这个是保留接口，方便我处理数据库
 */
var Bearcat = require('bearcat');
var Async = require("async")

module.exports = function () {
    return Bearcat.getBean({
        id: "get-addmotion",
        func: addmotion,
        props: [
            {name: "app", "ref": "application"}
        ]
    });
}

function addmotion() {
    this.app = null;
}

var CheckMotionDevice = function (msg) {
   if(msg.params.motion == undefined || msg.params.motionname == undefined || msg.params.motion.length < 8)
        return false;
  //  if(msg.params.motion.length != 40)
    //    return false;
    return true;
}
addmotion.prototype.handle = function (msg,next) {
    //if(!CheckMotionDevice(msg))
    {
        next(null,{code:101,msg:110});
        return;
    }

    var motionName = msg.params.motionname;
    var motion = msg.params.motion;
    var model = this.app.getComponent("dao").getConnection().model("MotionDevices");
    Async.waterfall(
        [
            function (cb) {
                model.invalidate(motion,function (invalid) {
                    if(invalid)
                        next(null, {code: 102, msg: ""});
                    else
                        cb()
                })
            },
            function () {
                model.addMotionDev({MotionDevice:motion,MotionName:motionName},function (res) {
                    if (res)
                        next(null, {code: 1, msg: "插入成功"});
                    else
                        next(null, {code: 101, msg: "插入失败"});
                });
            }
        ]
    );
}